import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, toLogin } from '@/utils/ssoUtils' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { findPermission } from '@/api/user'
import store from '@/store'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const CALL_PAGE_NAME = 'codeCallback'

router.beforeEach((to, from, next) => {
  // start progress bar
  NProgress.start();
  // set page title
  document.title = getPageTitle(to.meta.title)
  const token = getToken()
  if (to.name === CALL_PAGE_NAME) {
    next(); // 跳转
  } else if (!token) {
    toLogin();
  } else if (to.matched.some(record => record.meta.requireAuth)) {
    // 判断当前的token是否存在
    if (token) {
      findPermission().then(res => {
        if (res.result) {
          store.dispatch('user/setPermission', res.result).then(res => {
            next()
          })
        } else {
          next({ path: '/401' })
        }
      });
    } else {
      next({ path: '/' })
    }
  } else {
    next()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})